import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo853 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的目录根节点");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if(rootDir.isDirectory()){
            System.out.println("不是目录,退出");
            return;
        }
        System.out.println("请输入要搜索文件包含的名字");
        String token = scanner.next();
        List<File> result = new ArrayList<>();
        scanDir(rootDir,token,result);
        System.out.println("共找到了->");
        for (File file:result
        ) {
            System.out.println("请问您是否需要删除该文件");
            String str = scanner.next();
            if(str.toLowerCase().equals("yes")){
                file.delete();
            }
        }
    }

    private static void scanDir(File rootDir, String token, List<File> result) {
        File[] files = rootDir.listFiles();
        if(files==null || files.length==0){
            return;
        }
        for (int i = 0; i < files.length; i++) {
            if(files[i].isDirectory()){
                scanDir(files[i],token,result);
            }
            else if(isContain(files[i],token)){
                result.add(files[i].getAbsoluteFile());
            }

        }
    }

    private static boolean isContain(File file, String token) {
        StringBuffer stringBuffer = new StringBuffer();
        try(InputStream inputStream = new FileInputStream(file)){
            Scanner scanner = new Scanner(inputStream);
            while(scanner.hasNext()){
                String str = scanner.nextLine();
                stringBuffer.append(str);
            }
    } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return stringBuffer.indexOf(token) != -1;
    }
}
